package cn.admin.configcenter.registry.common.util;

import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.NullArgumentException;

public class RegexParser {

    public static String regexFormat(String regex) {
        if (regex == null) {
            throw new NullArgumentException("regex string can't be null");
        } else {
            StringBuffer result = new StringBuffer();
            result.append("^");

            for(int i = 0; i < regex.length(); ++i) {
                char ch = regex.charAt(i);
                if (!CharUtils.isAsciiAlphanumeric(ch) && !CharUtils.isAsciiNumeric(ch)) {
                    if (ch == '*') {
                        result.append("." + ch);
                    } else if (ch == '?') {
                        int j;
                        for(j = 0; j < regex.length() - i && ch == '?'; ++j) {
                            ch = regex.charAt(i + j);
                        }

                        if (j == regex.length() - i) {
                            result.append(".{" + j + "}");
                            break;
                        }

                        --j;
                        result.append(".{" + j + "}");
                        i += j - 1;
                    } else {
                        result.append("\\" + ch);
                    }
                } else {
                    result.append(ch);
                }
            }

            result.append("$");
            return result.toString();
        }
    }

    public static boolean containsWildcard(String regex) {
        return regex.contains("?") || regex.contains("*");
    }

}
